package Behavior;

import jade.core.*;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import Messages.AMessage;
import Agents.Messageable;
import Agents.Sensor.ASensor;

public class MeasureRequesterBehavior extends CyclicBehaviour
{
	private AMessage.Units unit;
	
	public MeasureRequesterBehavior(ASensor a, AMessage.Units agentsUnit)
	{
		super((Agent)a);
		unit = agentsUnit;
	}

	public void action() 
	{
		ACLMessage  msg = myAgent.receive();
		if(msg != null)
		{
			String content = msg.getContent();
			
			if(msg.getPerformative()== ACLMessage.INFORM)
			{
				if(content != null)
				{
					String[] sender = content.split("|");
					
					if( sender[0].substring(2).equalsIgnoreCase("FloorHeater") )
					{
						String[] contents = sender[1].split(",");
						
						if (contents[0].equalsIgnoreCase(AMessage.Units.TEMPERATURE.name()))
						{
							try { ((ASensor)myAgent).value = (Integer.parseInt(contents[1])); }
							catch (NumberFormatException e) { ; }
						}
					}
				}
			}
			else
			{			
				ACLMessage reply = msg.createReply();
	
				if(msg.getPerformative()== ACLMessage.REQUEST)
				{				
					if(content != null)
					{
						String[] sender = content.split("|");
						
						if( sender[0].substring(2).equalsIgnoreCase("FloorHeater") ||
						    sender[0].substring(2).equalsIgnoreCase("OfficeRegion") )
						{
							reply.setPerformative(ACLMessage.INFORM);
							reply.setContent(AMessage.constructMessage((Messageable)myAgent, AMessage.MessageType.MEASUREMENT));//MeasureUnits.measureResponse(myAgent, unit, ((ISensor)myAgent).getMeasuredValue())
						}
						else
						{
							reply.setPerformative(ACLMessage.REFUSE);
							reply.setContent("( UnexpectedContent ("+content+"))");
						}
					}
	
				}
				else 
				{
					reply.setPerformative(ACLMessage.NOT_UNDERSTOOD);
					reply.setContent("( (Unexpected-act "+ACLMessage.getPerformative(msg.getPerformative())+") )");   
				}
				myAgent.send(reply);
			}
		}
		else 
		{
			block();
		}
	}
}
